<template>
    <div class="home" ref="homeRef">
        <homeNavBar />
        <div class="banner">
            <img src="@/assets/img/home/banner.webp" alt="">
        </div>
        <homeSearchBox />
        <homeCategories />
        <div class="search-bar" v-if="isShowSearchBar">
            <searchBar :search-icon="true" @search-click="handleSearchClick" />
        </div>
        <homeContent />
    </div>
</template>

<script>
export default {
    name: "home"
}
</script>

<script setup>
import useHomeStore from '@/stores/modules/home';
import homeNavBar from './cpns/home-nav-bar.vue';
import homeSearchBox from './cpns/home-search-box.vue';
import homeCategories from './cpns/home-categories.vue';
import homeContent from './cpns/home-content.vue';
import searchBar from '@/components/search-bar/search-bar.vue';
import useScroll from '@/hooks/useScroll'
import { ref, watch, computed, onActivated } from 'vue';
import router from '@/router';
import { storeToRefs } from 'pinia';
import { formatMonthDay } from '@/utils/format_date';
import useMainStore from '@/stores/modules/main';
import useCityStore from '@/stores/modules/city';

const homeStore = useHomeStore()
homeStore.fetchHotSuggestData()
homeStore.fetchCategoriesDate()
homeStore.fetchHouseListDate()


// 监听window创建的滚动到底部'
const homeRef = ref()
const { isReachBottom, scrollTop } = useScroll(homeRef)
watch(isReachBottom, (newValue) => {
    if (newValue) {
        homeStore.fetchHouseListDate().then(() => {
            isReachBottom.value = false
        })
    }
})

// 搜索框显示控制
const isShowSearchBar = computed(() => {
    return scrollTop.value >= 350
})

// 跳转回home页面，保存原来的位置
onActivated(() => {
    homeRef.value?.scrollTo({
        top: scrollTop.value
    })
})

// 当前城市
const cityStore = useCityStore()
const { currentCity } = storeToRefs(cityStore)
const mainStore = useMainStore()
// 日期处理
const { startDate, endDate } = storeToRefs(mainStore)
const startDateStr = computed(() => formatMonthDay(startDate.value))
const endDateStr = computed(() => formatMonthDay(endDate.value))
// 搜索框点击事件
const handleSearchClick = () => {
    router.push({
        path: "/search",
        // 传递参数
        query: {
            startDate: startDate.value,
            endDate: endDate.value,
            currentCity: currentCity.value.cityName
        },
    });
}

</script>

<style lang="less" scoped>
.home {
    padding-bottom: 60px;
    height: 100vh;
    box-sizing: border-box;
    overflow-y: auto;
}

.banner {
    img {
        width: 100%;
    }
}

.search-bar {
    position: fixed;
    z-index: 9;
    top: 0;
    left: 0;
    right: 0;
    height: 45px;
    padding: 16px 16px 10px;
    background-color: #fff;
}
</style>
